package com.ruoyi.mobile.service.impl;


import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.mobile.domain.User;
import com.ruoyi.mobile.mapper.MessageMapper;
import com.ruoyi.mobile.mapper.UserMapper;
import com.ruoyi.mobile.model.vo.MessageContentVo;
import com.ruoyi.mobile.model.vo.MessageInfoVo;
import com.ruoyi.mobile.model.vo.MessageVo;
import com.ruoyi.mobile.service.IMessageService;
import com.ruoyi.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

@Service
public class MessageServiceImpl implements IMessageService {

    @Autowired
    public MessageMapper messageMapper;
    @Autowired
    public UserMapper userMapper;
    @Autowired
    public SysUserMapper sysUserMapper;

    @Override
    public List<MessageVo> getMessageList(int doctorId, int page) {
        if (page <= 1) {
            page = 1;
        }
        int pageSize = 10;
        int offset = (page - 1)*pageSize;
        List<Integer> idList = messageMapper.selectIdByDoctor(doctorId, offset, pageSize);
        if (idList == null || idList.isEmpty()) {
            return null;
        }
        return messageMapper.selectMessageList(idList);
    }

    @Override
    public MessageInfoVo getMessageInfo(int userId, Integer doctorId, int page, Integer lastId) {
        if (page <= 1) {
            page = 1;
        }
        int pageSize = 20;
        int offset = (page - 1)*pageSize;
        User user = userMapper.selectUserById(userId);
        SysUser sysUser = sysUserMapper.selectUserById(doctorId.longValue());
        if (sysUser == null) {
            throw new ServiceException("不存在的客服");
        }
        List<MessageContentVo> contentList = messageMapper.selectContentList(userId, doctorId, offset, pageSize, lastId);
        Collections.reverse(contentList);
        MessageInfoVo messageInfoVo = new MessageInfoVo();
        messageInfoVo.setAvatar(sysUser.getAvatar());
        messageInfoVo.setUserAvatar(user.getAvatar());
        messageInfoVo.setUsername(user.getNickname());
        messageInfoVo.setContentList(contentList);

        //每次只要一请求，就会把所有的未读消息都变成已读
        messageMapper.updateReadFlag(userId, doctorId);

        return messageInfoVo;
    }


}
